<template>
    <div>
      <button @click="visible = true">弹框</button>
  
      <button @click="changeAccount">改变账号</button>
  
      <a-modal
        title="广告计划主弹框"
        v-model:visible="visible"
        :maskClosable="false"
        :destroyOnClose="false"
        :confirmLoading="loading"
        width="1000px"
        height="600px"
        @ok="save"
      >
        <a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
          <a-form-item label="多账号分配" name="distribute_mode">
            <ButtonGroup
              :modelValue="formState.distribute_mode"
              @update:modelValue="handleDistributeModeChange"
              :values="[1, 2, 3, 4]"
              :isMutex="true"
              :labels="['多账号一致', '不同定向包', '不同标题包', '不同素材组']"
            />
          </a-form-item>
          <a-form-item label="创建方式" name="add_mode">
            <a-radio-group v-model:value="formState.add_mode">
              <a-radio-button :value="1">新建计划</a-radio-button>
              <a-radio-button :value="2" :disabled="isExistingPlanDisabled">已有计划</a-radio-button>
            </a-radio-group>
          </a-form-item>
  
          <!-- 新增：计划和广告组规则 -->
          <a-form-item label="计划和广告组规则" name="rule_distribute_mode">
            <a-radio-group v-model:value="formState.rule_distribute_mode">
              <template v-if="formState.add_mode === 1">
                <a-radio-button :value="1">一个计划多个广告组</a-radio-button>
                <a-radio-button :value="2">一个广告组一个计划</a-radio-button>
              </template>
              <template v-else>
                <a-radio-button :value="2">按广告顺序分计划</a-radio-button>
              </template>
            </a-radio-group>
          </a-form-item>
  
          <!-- 已有计划选择区域 -->
          <template v-if="formState.add_mode === 2">
            <a-form-item label="已有计划">
              <div style="display: flex; align-items: center">
                <span v-if="selectedPlans.length > 0" style="margin-right: 12px"> 已选择: {{ selectedPlans.length }}个计划 </span>
                <a-button type="primary" @click="openSelectCampaignModal">选择广告计划</a-button>
              </div>
            </a-form-item>
  
            <!-- 简化的已选计划展示区域 -->
            <a-form-item v-if="selectedPlans.length > 0" label="已选计划">
              <div class="selected-plans-simple">
                <div class="account-group" v-for="account in accountsWithPlans" :key="account.id">
                  <div class="account-header">
                    <span class="account-name">{{ account.name }}</span>
                    <span class="account-count">{{ getAccountSelectedCount(account.id) }}个计划</span>
                  </div>
                  <div class="plan-chips">
                    <a-tag
                      v-for="plan in getAccountPlans(account.id)"
                      :key="plan.id"
                      closable
                      @close="removePlan(plan.id)"
                      class="plan-chip"
                    >
                      {{ plan.name }} (ID: {{ plan.id }})
                    </a-tag>
                  </div>
                </div>
              </div>
            </a-form-item>
          </template>
  
          <!-- 以下字段仅在新建计划时显示 -->
          <template v-if="formState.add_mode === 1">
            <a-form-item label="投放范围" name="campaignType">
              <a-radio-group v-model:value="formState.campaignType">
                <a-radio-button :value="1">商店</a-radio-button>
                <a-radio-button :value="2">非商店</a-radio-button>
                <a-radio-button :value="3">米盟</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <a-form-item v-if="formState.campaignType === 2 || formState.campaignType === 3" label="投放方式" name="deliveryPolicy">
              <a-radio-group v-model:value="formState.deliveryPolicy">
                <a-radio-button :value="0">加速投放</a-radio-button>
                <a-radio-button :value="1">匀速投放</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <a-form-item label="流量优选" name="trafficMode">
              <a-checkbox
                :checked="!!formState.trafficMode"
                @change="(e: Event) => formState.trafficMode = (e.target as HTMLInputElement).checked ? 1 : 0"
              >
                开启流量优选
              </a-checkbox>
            </a-form-item>
  
            <!-- 计划名称字段 - 仅在新建计划时显示 -->
            <a-form-item label="计划名称" name="name">
              <a-input v-model:value="formState.name" placeholder="请输入计划名称" />
              <div class="dynamic-packet">
            插入动态词包：<span v-for="item in dynamicPacket" :key="item" @click="appendWord(item)">【{{ item }}】</span>
          </div>
            </a-form-item>
  
            <!-- 添加随机ID后缀字段 -->
            <a-form-item label="加入随机ID后缀" name="auto_suffix_id">
              <a-radio-group v-model:value="formState.auto_suffix_id">
                <a-radio-button :value="true">是</a-radio-button>
                <a-radio-button :value="false">否</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <a-form-item label="预算" name="budget">
              <a-input-number
                v-model:value="formState.budget"
                :min="200"
                :max="100000000"
                :precision="0"
                addon-after="元/天"
                style="width: 200px"
                @change="(value: number | null) => (formState.budget = String(value))"
              />
            </a-form-item>
  
            <!-- 修改自动优化字段，只显示"开启"选项 -->
            <a-form-item label="自动优化" name="autoOptimize">
              <a-radio-group v-model:value="formState.autoOptimize">
                <a-radio-button :value="true">开启</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <!-- 由于自动优化始终开启，投放场景始终显示 -->
            <a-form-item label="投放场景" name="scenario">
              <a-radio-group v-model:value="formState.scenario">
                <a-radio-button :value="0">日常投放</a-radio-button>
                <a-radio-button :value="1">增量投放</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <a-form-item label="投放时间" name="scheduleType">
              <a-date-picker
                v-model:value="startDate"
                format="YYYY-MM-DD"
                style="width: 200px"
                :disabledDate="disabledStartDate"
                @change="(date: dayjs.Dayjs | null, dateString: string) => (formState.startDate = dateString)"
              />
              <a-form-item-rest>
                <span style="margin: 0 8px">至</span>
                <a-date-picker
                  v-model:value="endDate"
                  format="YYYY-MM-DD"
                  style="width: 200px"
                  :disabledDate="disabledEndDate"
                  :disabled="formState.endDate === '9999-12-31'"
                  @change="(date: dayjs.Dayjs | null, dateString: string) => (formState.endDate = dateString)"
                />
                <a-checkbox :checked="formState.endDate === '9999-12-31'" style="margin-left: 12px" @change="handleLongTermChange">
                  长期投放
                </a-checkbox>
              </a-form-item-rest>
            </a-form-item>
  
            <!-- 转化追踪字段 -->
            <a-form-item label="转化追踪" name="conversionTracking">
              <div style="display: flex; align-items: center">
                <span v-if="selectedConversions.length > 0" style="margin-right: 12px">
                  已选择: {{ selectedConversions.length }}个转化追踪
                </span>
                <a-button type="primary" @click="openSelectConversionModal"> 选择转化追踪 </a-button>
              </div>
            </a-form-item>
  
            <!-- 简化的已选转化追踪展示区域 -->
            <a-form-item v-if="selectedConversions.length > 0" label="已选转化追踪">
              <div class="selected-conversions-simple">
                <div class="account-group" v-for="account in accountsWithConversions" :key="account.id">
                  <div class="account-header">
                    <span class="account-name">{{ account.name }}</span>
                    <span class="account-count">{{ getAccountConversionCount(account.id) }}个转化追踪</span>
                  </div>
                  <div class="conversion-chips">
                    <a-tag
                      v-for="conversion in getAccountConversions(account.id)"
                      :key="conversion.conversionId || conversion.id"
                      closable
                      @close="removeConversion(conversion.conversionId || conversion.id || 0)"
                      class="conversion-chip"
                    >
                      {{ conversion.name || conversion.conversionName }} 
                      ({{ conversion.type || `类型${conversion.conversionType}` }})
                    </a-tag>
                  </div>
                </div>
              </div>
            </a-form-item>
  
            <!-- 出价方式字段 -->
            <a-form-item label="出价方式" name="bid_mode">
              <a-radio-group v-model:value="formState.bid_mode">
                <a-radio-button :value="1">统一设置</a-radio-button>
                <a-radio-button :value="2">多账户分别设置</a-radio-button>
              </a-radio-group>
            </a-form-item>
  
            <!-- 统一设置模式下的出价 -->
            <a-form-item v-if="formState.bid_mode === 1" label="出价" name="converBidMap">
              <a-tabs v-model:activeKey="unifiedBidType" type="card" class="bid-tabs">
                <a-tab-pane key="NORMAL_BID" tab="正常出价">
                  <div class="bid-input-container">
                    <a-input-number
                      v-model:value="unifiedBidValue"
                      :min="3"
                      :max="9999"
                      :precision="2"
                      style="width: 200px"
                      addon-after="元"
                    />
                  </div>
                  <div class="bid-tip">出价上限：9999元</div>
                </a-tab-pane>
                
                <a-tab-pane key="RANDOM_BID" tab="随机出价">
                  <div class="bid-input-container">
                    <a-input-number
                      v-model:value="unifiedBidRangeMin"
                      :min="3"
                      :max="9999"
                      :precision="2"
                      style="width: 120px"
                    />
                    <span class="range-separator">-</span>
                    <a-input-number
                      v-model:value="unifiedBidRangeMax"
                      :min="unifiedBidRangeMin || 3"
                      :max="9999"
                      :precision="2"
                      style="width: 120px"
                    />
                    <span class="addon-text">元</span>
                  </div>
                  <div class="bid-tip">出价上限：9999元 出价将在该范围内随机生成</div>
                </a-tab-pane>
  
                <!-- 在统一设置模式下添加梯度出价选项卡 -->
                <a-tab-pane key="GRADIENT_BID" tab="梯度出价">
                  <div class="bid-input-container">
                    <a-input-number
                      v-model:value="unifiedBidRangeMin"
                      :min="3"
                      :max="9999"
                      :precision="2"
                      style="width: 120px"
                    />
                    <span class="range-separator">-</span>
                    <a-input-number
                      v-model:value="unifiedBidRangeMax"
                      :min="unifiedBidRangeMin || 3"
                      :max="9999"
                      :precision="2"
                      style="width: 120px"
                    />
                    <span class="addon-text">元</span>
                  </div>
                  <div class="bid-tip">出价上限：9999元 根据创建的广告数量阶梯设置出价</div>
                </a-tab-pane>
              </a-tabs>
            </a-form-item>
  
            <!-- 多账户分别设置模式下的出价 -->
            <a-form-item v-else label="出价" name="converBidMap">
              <div class="multi-account-bid-container">
                <a-button type="primary" @click="openSetConverBidModal">
                  设置多账户出价
                </a-button>
                <div v-if="hasSetMultiAccountBid" class="multi-account-bid-summary">
                  已设置 {{ getConfiguredAccountCount() }} 个账户的出价
                </div>
              </div>
            </a-form-item>
  
            <!-- 开启状态字段 - 仅在新建计划时显示 -->
            <a-form-item label="开启状态" name="pause">
              <a-radio-group v-model:value="formState.pause">
                <a-radio-button :value="0">关闭</a-radio-button>
                <a-radio-button :value="1">开启</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </template>
        </a-form>
      </a-modal>
  
      <!-- 使用选择广告计划组件 - 每次重新创建 -->
      <SelectedPlanModal
        v-if="showPlanModal"
        ref="selectedPlanModal"
        :selectedPlans="selectedPlans"
        :key="planModalKey"
        @select="handlePlanSelected"
      />
  
      <!-- 使用选择转化追踪组件 - 每次重新创建 -->
      <SelectedConversionModal
        v-if="showConversionModal"
        ref="selectedConversionModal"
        :selectedConversions="selectedConversions"
        :accountList="accountList"
        :key="conversionModalKey"
        @select="handleConversionSelected"
        @add-new="openAddConversionModal"
      />
  
      <!-- 使用新建转化追踪组件 -->
      <AddConversionModal ref="addConversionModalRef" :accountList="accountList" @success="handleAddConversionSuccess" />
  
      <!-- 使用 SetConverBid 组件 -->
      <SetConverBid
        ref="setConverBidModal"
        @update="handleMultiAccountBidSet"
      />
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive, watch, computed, onMounted } from "vue";
  import { Form } from "ant-design-vue";
  import dayjs from "dayjs";
  import ButtonGroup from "@/components/ButtonGroup.vue";
  import SelectedPlanModal from "./SelectedPlanModal.vue";
  import SelectedConversionModal from "./SelectedConversionModal.vue";
  import AddConversionModal from "./AddConversionModal.vue";
  import SetConverBid from './SetConverBid.vue';
  import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";
  
  // 定义接口
  interface Account {
    id: number;
    name: string;
  }
  
  interface Plan {
    id: number;
    name: string;
    budget?: number;
    status?: string;
    targetLen?: number;
    titleLen?: number;
    creativeLen?: number;
  }
  
  interface Conversion {
    id?: number;
    conversionId: number;
    name: string;
    type: string;
    conversionName?: string;
    conversionType?: number;
    trackingType?: number;
    conversionSource?: number;
    conversionStatus?: number;
    customerId?: number;
    sourceType?: number;
    appId?: number;
  }
  
  interface FormState {
    distribute_mode: number[];
    add_mode: number;
    campaignType: number;
    trafficMode: number;
    budget: string;
    deliveryPolicy: number;
    autoOptimize: boolean;
    scenario: number;
    productType: number;
    startDate: string;
    endDate: string;
    conversionTracking: number;
    name: string;
    auto_suffix_id: boolean;
    plan_map?: Record<number, number[]>;
    conversion_map?: Record<number, number>;
    rule_distribute_mode: number;
    pause: number;
    bid_mode: number;
    converBidMap: any;
  }
  
  
  const useForm = Form.useForm;
  const visible = ref(false);
  const loading = ref(false);
  const startDate = ref<dayjs.Dayjs | null>(null);
  const endDate = ref<dayjs.Dayjs | null>(null);
  const selectedPlanModal = ref();
  const selectedConversionModal = ref();
  const selectedPlans = ref<Plan[]>([]);
  const selectedConversions = ref<Conversion[]>([]);
  const viewingAccountId = ref<number | null>(null);
  const viewingConversionAccountId = ref<number | null>(null);
  // 控制是否显示计划选择弹窗
  const showPlanModal = ref(false);
  // 控制是否显示转化追踪选择弹窗
  const showConversionModal = ref(false);
  // 用于强制重新渲染组件的key
  const planModalKey = ref(0);
  const conversionModalKey = ref(0);
  
  // 插入动态词包
  const appendWord = (word: string) => {
    formState.name += `[${word}]`;
  };
  
  // 动态词包
  const dynamicPacket = reactive([
    "项目名称",
    "账户标签",
    "账户备注",
    "创建日期",
    "创建时间",
    "定向包名",
    "标题包名",
    "营销目标",
    "下发日期",
    "下发日期时间",
  ]);
  
  const formState = reactive<FormState>({
    distribute_mode: [1],
    add_mode: 1,
    campaignType: 1,
    trafficMode: 0,
    budget: "200",
    deliveryPolicy: 0,
    autoOptimize: true,
    scenario: 0,
    productType: 1,
    startDate: "",
    endDate: "",
    conversionTracking: 0,
    name: "",
    auto_suffix_id: false,
    rule_distribute_mode: 1,
    pause: 1,
    bid_mode: 1,
    converBidMap: {
      type: "NORMAL_BID",
      value: 66
    },
  });
  
  const rules = {
    distribute_mode: [{ required: true, message: "请选择多账号分配方式" }],
    add_mode: [{ required: true, message: "请选择创建方式" }],
    campaignType: [{ required: true, message: "请选择投放范围" }],
    budget: [{ required: true, message: "请输入预算" }],
    // 仅在新建计划时验证计划名称
    name: [
      {
        required: true,
        message: "请输入计划名称",
        // 仅在新建计划时验证
        validator: (rule: any, value: string) => {
          if (formState.add_mode === 1 && !value) {
            return Promise.reject("请输入计划名称");
          }
          return Promise.resolve();
        },
      },
    ],
  };
  
  const formRef = ref();
  const { validate } = useForm(formState, rules);
  
  // 禁用今天之前的日期
  const disabledStartDate = (current: dayjs.Dayjs | null) => {
    return current && current < dayjs().startOf("day");
  };
  
  // 禁用开始日期之前的日期
  const disabledEndDate = (current: dayjs.Dayjs | null) => {
    return current && (current < dayjs().startOf("day") || (startDate.value && current < dayjs(startDate.value).startOf("day")));
  };
  
  const handleLongTermChange = (e: { target: { checked: boolean } }) => {
    if (e.target.checked) {
      // 如果选择长期投放，设置结束日期为无限远
      formState.endDate = "9999-12-31";
      endDate.value = null;
    } else {
      // 如果取消长期投放，设置默认结束日期为30天后
      const defaultEndDate = dayjs(startDate.value).add(30, "day");
      endDate.value = defaultEndDate;
      formState.endDate = defaultEndDate.format("YYYY-MM-DD");
    }
  };
  
  // 使用 store 中的账号列表
  const store = batchCreateAdStore();
  
  // 初始化为空数组，完全依赖 store 提供的账号列表
  const accountList = ref<Account[]>([]);
  
  // 在组件挂载时从 store 获取账号列表
  onMounted(() => {
    if (store.AccountItems && store.AccountItems.length > 0) {
      accountList.value = store.AccountItems;
    } else {
      // 如果 store 中没有账号，使用默认账号（仅用于开发测试）
      accountList.value = [
        { id: 1, name: "广告账号A" },
        { id: 2, name: "广告账号B" },
      ];
    }
  });
  
  // 监听账号列表变化
  watch(
    () => accountList.value,
    (newAccounts, oldAccounts) => {
      if (!newAccounts || !oldAccounts) return;
  
      // 如果账号数量减少，需要清理已选计划中不存在账号的计划
      const newAccountIds = new Set(newAccounts.map((acc) => acc.id));
  
      // 过滤掉不存在账号的计划
      selectedPlans.value = selectedPlans.value.filter((plan) => {
        const accountId = Math.floor(plan.id / 100);
        return newAccountIds.has(accountId);
      });
  
      // 更新当前查看的账号
      if (viewingAccountId.value && !newAccountIds.has(viewingAccountId.value)) {
        // 如果当前查看的账号已被移除，重置为第一个有计划的账号
        const accountWithPlans = newAccounts.find((account) => getAccountSelectedCount(account.id) > 0);
  
        if (accountWithPlans) {
          viewingAccountId.value = accountWithPlans.id;
        } else {
          viewingAccountId.value = null;
        }
      }
  
      // 同步更新弹窗中的已选计划
      if (selectedPlanModal.value && selectedPlanModal.value.updateSelectedPlans) {
        selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
      }
  
      // 同步更新弹窗中的账号列表
      if (selectedPlanModal.value && selectedPlanModal.value.updateAccountList) {
        selectedPlanModal.value.updateAccountList(newAccounts);
      }
    },
    { deep: true }
  );
  
  const changeAccount = () => {
    accountList.value = [
      {
        id: 111111111111111,
        name: "广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A广告账号A",
      },
    ];
  
    // 直接调用监听器可能无法触发，所以在这里也手动同步一次
    // 过滤掉不存在账号的计划
    const newAccountIds = new Set(accountList.value.map((acc) => acc.id));
    selectedPlans.value = selectedPlans.value.filter((plan) => {
      const accountId = Math.floor(plan.id / 100);
      return newAccountIds.has(accountId);
    });
  
    // 更新弹窗中的数据
    if (selectedPlanModal.value) {
      // 先更新已选计划，再更新账号列表
      selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
      selectedPlanModal.value.updateAccountList(accountList.value);
    }
  };
  
  const save = () => {
    validate()
      .then(() => {
        // 克隆表单数据，避免修改原始数据
        const submitData = { ...formState };
        
        // 如果启用了随机ID后缀，并且是新建计划模式
        if (submitData.auto_suffix_id && submitData.add_mode === 1) {
          // 生成一个6位随机数字ID
          const randomId = Math.floor(100000 + Math.random() * 900000);
          // 添加到计划名称后面
          submitData.name = `${submitData.name}_${randomId}`;
        }
        
        console.log("表单数据:", submitData);
        
        // 继续原有的提交逻辑...
      })
      .catch((error) => {
        console.log("验证失败", error);
      });
  };
  
  const openSelectCampaignModal = () => {
    // 先隐藏组件，确保组件会被销毁
    showPlanModal.value = false;
  
    // 增加key值，强制重新渲染组件
    planModalKey.value++;
  
    // 短暂延迟后再显示组件，确保组件被完全销毁和重新创建
    setTimeout(() => {
      // 显示组件
      showPlanModal.value = true;
  
      // 等待组件加载完成后再操作
      setTimeout(() => {
        if (selectedPlanModal.value) {
          // 先更新已选计划，再显示弹窗
          selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
          selectedPlanModal.value.updateAccountList(accountList.value);
          selectedPlanModal.value.show();
        }
      }, 50); // 增加延迟时间，确保组件完全加载
    }, 0);
  };
  
  const accountsWithPlans = computed(() => {
    return accountList.value.filter((account) => getAccountSelectedCount(account.id) > 0);
  });
  
  const filteredSelectedPlans = computed(() => {
    if (!viewingAccountId.value) return [];
    return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === viewingAccountId.value);
  });
  
  const getAccountSelectedCount = (accountId: number) => {
    return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId).length;
  };
  
  const handlePlanSelected = (plans: Plan[]) => {
    selectedPlans.value = plans;
    if (plans.length > 0) {
      const firstAccountId = Math.floor(plans[0].id / 100);
      viewingAccountId.value = firstAccountId;
    } else {
      viewingAccountId.value = null;
    }
  
    // 选择完成后隐藏弹窗组件
    showPlanModal.value = false;
  };
  
  const removePlan = (planId: number) => {
    // 从已选计划中移除
    selectedPlans.value = selectedPlans.value.filter((plan) => plan.id !== planId);
  
    // 更新当前查看的账号
    if (filteredSelectedPlans.value.length === 0) {
      const accountWithPlans = accountList.value.find((account) => getAccountSelectedCount(account.id) > 0);
  
      if (accountWithPlans) {
        viewingAccountId.value = accountWithPlans.id;
      } else {
        viewingAccountId.value = null;
      }
    }
  
    // 同步更新弹窗中的已选计划
    if (selectedPlanModal.value && selectedPlanModal.value.updateSelectedPlans) {
      selectedPlanModal.value.updateSelectedPlans(selectedPlans.value);
    }
  };
  
  // 初始化日期
  watch(
    () => visible.value,
    (newVal) => {
      if (newVal) {
        // 当弹窗打开时，初始化日期
        const today = dayjs();
        startDate.value = today;
        formState.startDate = today.format("YYYY-MM-DD");
  
        // 判断是否为长期投放
        if (formState.endDate === "9999-12-31") {
          endDate.value = null;
        } else {
          const defaultEndDate = today.add(30, "day");
          endDate.value = defaultEndDate;
          formState.endDate = defaultEndDate.format("YYYY-MM-DD");
        }
      } else {
        // 重置表单
        formState.startDate = "";
        formState.endDate = "";
        startDate.value = null;
        endDate.value = null;
      }
    }
  );
  
  // 监听创建方式变化
  watch(
    () => formState.add_mode,
    (newVal) => {
      if (newVal === 2) {
        // 如果选择了已有计划，重置选择的计划
        selectedPlans.value = [];
      } else {
        // 如果选择了新建计划，重置计划名称
        formState.name = "";
      }
    }
  );
  
  // 监听投放范围变化
  watch(
    () => formState.campaignType,
    (newVal) => {
      // 当投放范围不是非商店或米盟时，重置投放方式为默认值
      if (newVal !== 2 && newVal !== 3) {
        formState.deliveryPolicy = 0;
      }
    }
  );
  
  // 获取指定账户的所有计划
  const getAccountPlans = (accountId: number) => {
    return selectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId);
  };
  
  // 监听计划选择弹窗的关闭事件
  watch(
    () => selectedPlanModal.value,
    (newVal) => {
      if (newVal) {
        // 监听弹窗关闭事件
        const originalHide = newVal.hide;
        newVal.hide = () => {
          originalHide();
          // 立即销毁组件
          showPlanModal.value = false;
        };
      }
    },
    { immediate: true }
  );
  
  // 计算属性：判断是否禁用已有计划选项
  const isExistingPlanDisabled = computed(() => {
    // 当多账号分配包含"不同定向包"(值为2)时，禁用已有计划选项
    return formState.distribute_mode.includes(2);
  });
  
  // 处理多账号分配方式变化
  const handleDistributeModeChange = (val: number[]) => {
    formState.distribute_mode = val;
  
    // 当选择了不同定向包时，强制设置为新建计划
    if (val.includes(2)) {
      formState.add_mode = 1;
  
      // 如果有已选计划，清空它们，但不显示提示信息
      if (selectedPlans.value.length > 0) {
        selectedPlans.value = [];
      }
    }
  };
  
  // 打开选择转化追踪弹窗
  const openSelectConversionModal = () => {
    // 先隐藏组件，确保组件会被销毁
    showConversionModal.value = false;
  
    // 增加key值，强制重新渲染组件
    conversionModalKey.value++;
  
    // 短暂延迟后再显示组件，确保组件被完全销毁和重新创建
    setTimeout(() => {
      // 显示组件
      showConversionModal.value = true;
  
      // 等待组件加载完成后再操作
      setTimeout(() => {
        if (selectedConversionModal.value) {
          // 确保传递的数据中包含 conversionId 字段
          const conversionsWithCorrectIds = selectedConversions.value.map(conversion => ({
            id: conversion.id || conversion.conversionId,
            // 先解构其他字段，然后再覆盖特定字段
            ...conversion,
            conversionId: conversion.conversionId || conversion.id,
            name: conversion.name || conversion.conversionName || '',
            type: conversion.type || `类型${conversion.conversionType || 0}`,
          }));
          
          selectedConversionModal.value.updateSelectedConversions(conversionsWithCorrectIds);
          selectedConversionModal.value.updateAccountList(accountList.value);
          selectedConversionModal.value.show();
        }
      }, 50);
    }, 0);
  };
  
  // 处理转化追踪选择
  const handleConversionSelected = (conversions: Conversion[]) => {
    // 统一字段格式，确保 id 和 conversionId 都存在
    selectedConversions.value = conversions.map(conversion => ({
      id: conversion.id || conversion.conversionId,
      // 先解构其他字段，然后再覆盖特定字段
      ...conversion,
      conversionId: conversion.conversionId || conversion.id,
      name: conversion.name || conversion.conversionName || '',
      type: conversion.type || `类型${conversion.conversionType || 0}`,
    }));
  
    // 设置表单状态
    if (selectedConversions.value.length > 0) {
      formState.conversionTracking = 1;
      
      // 设置当前查看的账号为第一个有转化追踪的账号
      const firstAccountId = Math.floor(selectedConversions.value[0].conversionId / 100);
      viewingConversionAccountId.value = firstAccountId;
    } else {
      viewingConversionAccountId.value = null;
      formState.conversionTracking = 0;
    }
  
    // 选择完成后隐藏弹窗组件
    showConversionModal.value = false;
  };
  
  // 获取指定账户的所有转化追踪 - 修改为使用 conversionId
  const getAccountConversions = (accountId: number) => {
    return selectedConversions.value.filter((conversion) => {
      const conversionId = conversion.conversionId || conversion.id || 0;
      return Math.floor(conversionId / 100) === accountId;
    });
  };
  
  // 获取指定账号已选转化追踪数量 - 修改为使用 conversionId
  const getAccountConversionCount = (accountId: number) => {
    return selectedConversions.value.filter((conversion) => {
      const conversionId = conversion.conversionId || conversion.id || 0;
      return Math.floor(conversionId / 100) === accountId;
    }).length;
  };
  
  // 移除转化追踪
  const removeConversion = (conversionId: number) => {
    // 从已选转化追踪中移除
    selectedConversions.value = selectedConversions.value.filter((conversion) => conversion.id !== conversionId);
  
    // 更新当前查看的账号
    if (viewingConversionAccountId.value) {
      const accountConversions = getAccountConversions(viewingConversionAccountId.value);
      if (accountConversions.length === 0) {
        const accountWithConversions = accountList.value.find((account) => getAccountConversionCount(account.id) > 0);
  
        if (accountWithConversions) {
          viewingConversionAccountId.value = accountWithConversions.id;
        } else {
          viewingConversionAccountId.value = null;
        }
      }
    }
  
    // 同步更新弹窗中的已选转化追踪
    if (selectedConversionModal.value && selectedConversionModal.value.updateSelectedConversions) {
      selectedConversionModal.value.updateSelectedConversions(selectedConversions.value);
    }
  };
  
  // 计算有转化追踪的账号
  const accountsWithConversions = computed(() => {
    return accountList.value.filter((account) => getAccountConversionCount(account.id) > 0);
  });
  
  // 监听转化追踪选择弹窗的关闭事件
  watch(
    () => selectedConversionModal.value,
    (newVal) => {
      if (newVal) {
        // 监听弹窗关闭事件
        const originalHide = newVal.hide;
        newVal.hide = () => {
          originalHide();
          // 立即销毁组件
          showConversionModal.value = false;
        };
      }
    },
    { immediate: true }
  );
  
  // 新建转化追踪相关
  const addConversionModalRef = ref();
  
  // 打开新建转化追踪弹框
  const openAddConversionModal = () => {
    if (addConversionModalRef.value) {
      addConversionModalRef.value.show();
    }
  };
  
  // 处理新建转化追踪成功
  const handleAddConversionSuccess = (newConversion: Conversion) => {
    // 不自动添加到已选转化追踪列表
    // selectedConversions.value.push(newConversion);
  
    // 不自动更新转化追踪状态
    // formState.conversionTracking = 1;
  
    // 不自动设置当前查看的账号
    // if (selectedConversions.value.length === 1) {
    //     viewingConversionAccountId.value = Math.floor(newConversion.id / 100);
    // }
  
    // 通知转化追踪选择弹窗刷新列表
    if (selectedConversionModal.value && selectedConversionModal.value.addNewConversion) {
      selectedConversionModal.value.addNewConversion(newConversion);
    }
  };
  
  // 监听创建方式变化，自动调整计划和广告组规则
  watch(
    () => formState.add_mode,
    (newVal) => {
      // 当创建方式变为"已有计划"时，自动设置规则为"按广告顺序分计划"
      if (newVal === 2) {
        formState.rule_distribute_mode = 2;
      } else {
        // 当创建方式变为"新建计划"时，默认设置为"一个计划多个广告组"
        formState.rule_distribute_mode = 1;
      }
    }
  );
  
  // 用于统一设置模式下的出价类型
  const unifiedBidType = ref("NORMAL_BID");
  
  // 用于统一设置模式下的出价值
  const unifiedBidValue = ref(66);
  
  // 用于统一设置模式下的出价范围
  const unifiedBidRangeMin = ref(3);
  const unifiedBidRangeMax = ref(100);
  
  // 标记是否已设置多账户出价
  const hasSetMultiAccountBid = ref(false);
  
  // 获取已配置出价的账户数量
  const getConfiguredAccountCount = () => {
    if (!formState.converBidMap) return 0;
    
    // 过滤掉 unified 键，只计算账户ID
    return Object.keys(formState.converBidMap).filter(key => key !== 'unified').length;
  };
  
  // 在组件引用部分添加
  const setConverBidModal = ref();
  
  // 修改打开设置多账户出价弹框的方法
  const openSetConverBidModal = () => {
    if (setConverBidModal.value) {
      setConverBidModal.value.show(formState.converBidMap, accountList.value);
    }
  };
  
  // 添加处理多账户出价设置完成的方法
  const handleMultiAccountBidSet = (bidMap: any) => {
    formState.converBidMap = bidMap;
    hasSetMultiAccountBid.value = true;
  };
  
  // 监听出价类型变化
  watch(unifiedBidType, (newType) => {
    // 更新表单中的出价类型
    if (formState.bid_mode === 1) {
      if (newType === "NORMAL_BID") {
        formState.converBidMap = {
          type: newType,
          value: unifiedBidValue.value
        };
      } else {
        formState.converBidMap = {
          type: newType,
          value: {
            min: unifiedBidRangeMin.value,
            max: unifiedBidRangeMax.value
          }
        };
      }
    }
  });
  
  // 监听正常出价值变化
  watch(unifiedBidValue, (newValue) => {
    if (formState.bid_mode === 1 && unifiedBidType.value === "NORMAL_BID") {
      formState.converBidMap = {
        type: "NORMAL_BID",
        value: newValue
      };
    }
  });
  
  // 监听出价范围变化
  watch([unifiedBidRangeMin, unifiedBidRangeMax], ([newMin, newMax]) => {
    if (formState.bid_mode === 1 && 
        (unifiedBidType.value === "RANDOM_BID" || unifiedBidType.value === "GRADIENT_BID")) {
      formState.converBidMap = {
        type: unifiedBidType.value,
        value: {
          min: newMin,
          max: newMax
        }
      };
    }
  });
  
  // 监听出价方式变化
  watch(() => formState.bid_mode, (newMode) => {
    if (newMode === 1) {
      // 切换到统一设置模式
      // 如果之前已经设置了统一配置，则使用它
      if (formState.converBidMap.unified) {
        const unifiedConfig = formState.converBidMap.unified;
        unifiedBidType.value = unifiedConfig.type;
        
        if (unifiedConfig.type === "NORMAL_BID") {
          unifiedBidValue.value = unifiedConfig.value;
        } else {
          unifiedBidRangeMin.value = unifiedConfig.value.min;
          unifiedBidRangeMax.value = unifiedConfig.value.max;
        }
        
        // 更新表单数据
        formState.converBidMap = unifiedConfig;
      } else {
        // 如果没有统一配置，则创建默认配置
        formState.converBidMap = {
          type: "NORMAL_BID",
          value: 66
        };
        unifiedBidType.value = "NORMAL_BID";
        unifiedBidValue.value = 66;
      }
    } else {
      // 切换到多账户分别设置模式
      // 保存当前统一配置
      const currentConfig = { ...formState.converBidMap };
      
      // 初始化多账户配置
      const multiAccountConfig: Record<string, any> = {};
      multiAccountConfig.unified = currentConfig;
      
      formState.converBidMap = multiAccountConfig;
    }
  });
  
  // 初始化统一设置值
  onMounted(() => {
    // 如果有初始值，则使用它
    if (formState.converBidMap) {
      if (formState.converBidMap.type) {
        unifiedBidType.value = formState.converBidMap.type;
        
        if (formState.converBidMap.type === "NORMAL_BID") {
          unifiedBidValue.value = formState.converBidMap.value;
        } else if (formState.converBidMap.value && typeof formState.converBidMap.value === 'object') {
          unifiedBidRangeMin.value = formState.converBidMap.value.min || 3;
          unifiedBidRangeMax.value = formState.converBidMap.value.max || 100;
        }
      }
    }
  });
  
  </script>
  
  <style scoped lang="less">
  .selected-plans-simple {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    padding: 12px;
  }
  
  .account-group {
    margin-bottom: 16px;
  }
  
  .account-group:last-child {
    margin-bottom: 0;
  }
  
  .account-header {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .account-name {
    font-weight: bold;
    flex: 1;
  }
  
  .account-count {
    color: #999;
    font-size: 12px;
  }
  
  .plan-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .plan-chip {
    margin-right: 0;
    padding: 4px 8px;
  }
  
  .selected-conversions-simple {
    max-height: 300px;
    overflow-y: auto;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    padding: 12px;
    margin-bottom: 16px;
  }
  
  .conversion-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .conversion-chip {
    margin-right: 0;
    padding: 4px 8px;
  }
  
  .empty-conversions {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    margin-bottom: 16px;
  }
  
  .dynamic-packet {
    background-color: #f0f0f0;
    padding: 5px 15px;
    margin-top: 10px;
  }
  .dynamic-packet span {
    cursor: pointer;
    color: #1890ff;
  }
  
  .bid-tabs {
    width: 100%;
  }
  
  .bid-input-container {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
  }
  
  .range-separator {
    margin: 0 8px;
    color: #999;
  }
  
  .addon-text {
    margin-left: 8px;
    color: #999;
  }
  
  .bid-tip {
    color: #999;
    font-size: 12px;
  }
  
  .multi-account-bid-summary {
    margin-top: 8px;
    font-size: 14px;
    color: #1890ff;
  }
  </style>
  